package com.javaex.book.utils;

/**
 * 分页
 *
 * @author 黄星琦
 * @Date 2022年2月17日
 */
public class Pagination {
	
	public static final Integer DEFAULT_PAGE_NO = 1;
	public static final Integer DEFAULT_PAGE_SIZE = 10;

	/** 页码 */
	private Integer no;
	
	/** 页容量（每页数据数量） */
	private Integer size;
	
	/** 总页数 */
	private Integer total;
	
	/** 共记录数（总数据数量） */
	private Integer totalCount;
	
	/** 查询SQL的开始位置 */
	private Integer start;
	
	/** 上一页 */
	private Integer prev;
	
	/** 下一页 */
	private Integer next;
	
	/** 要跳转的页面URL */
	private String url;
	
	/** 当前页的数据 */
	private Object data;
	
	public Pagination(Integer no, Integer size, Integer totalCount) {
		if (no <= 0) no = 1;
		this.no = no;
		if (size <= 0) size = DEFAULT_PAGE_SIZE;
		this.size = size;
		if (totalCount < 0) totalCount = 0;
		this.totalCount = totalCount;
		// 计算总页数
		this.calculaPageTotal();
		// 计算开始位置
		this.start = (this.no - 1) * this.size; 
		if (no > this.total) no = this.total;
		// 上一页
		this.prev = this.no - 1;
		if (this.prev <= 0) this.prev = 1;
		// 下一页
		this.next = this.no + 1;
		if (this.next > this.total) this.next = this.total;
	}
	
	/**
	 * 计算总页数
	 */
	private void calculaPageTotal() {
		// 如果总记录数小于等于页容量，只有1页
		if (this.totalCount <= 0) {
			this.total = 0;
			return;
		}
		if (this.totalCount <= this.size) {
			this.total  = 1;
			return;
		}
		// 如果 totalCount % size == 0，则有（totalCount / size）页
		// 如果 totalCount % size > 0，则有（totalCount / size + 1）页
		this.total = this.totalCount / this.size;
		if (this.totalCount % this.size > 0) {
			this.total++;
		} 
	}

	public Integer getNo() {
		return no;
	}

	public Integer getSize() {
		return size;
	}

	public Integer getTotal() {
		return total;
	}

	public Integer getTotalCount() {
		return totalCount;
	}

	public Integer getStart() {
		return start;
	}
	
	public Integer getPrev() {
		return prev;
	}

	public Integer getNext() {
		return next;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	@Override
	public String toString() {
		return "Pagination [no=" + no + ", size=" + size + ", total=" + total + ", totalCount=" + totalCount + "]";
	}
}
